package com.whisper.application.app.web.service.impl;

import com.whisper.application.app.web.entities.LoginBody;
import com.whisper.application.app.web.service.IFrontLoginService;
import com.whisper.application.app.web.service.TokenService;
import com.whisper.application.service.domain.VrUser;
import com.whisper.application.service.service.IVrUserService;
import com.whisper.cache.service.CacheService;
import com.whisper.common.constant.CacheConstants;
import com.whisper.common.constant.UserConstants;
import com.whisper.common.exception.ServiceException;
import com.whisper.common.exception.argument.ArgumentIllegalException;
import com.whisper.common.exception.argument.ArgumentRepeatException;
import com.whisper.common.exception.user.*;
import com.whisper.common.security.context.AuthenticationContextHolder;
import com.whisper.common.security.model.LoginUser;
import com.whisper.common.security.util.SecurityUtils;
import com.whisper.common.utils.DateUtils;
import com.whisper.common.utils.StringUtils;
import com.whisper.common.utils.ip.IpUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class FrontLoginServiceImpl implements IFrontLoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IVrUserService userService;

    @Autowired
    private CacheService cacheService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public String login(String username, String password, String code, String uuid) {

        // 验证码校验
        validateCaptcha(code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e)
        {
            if (e instanceof BadCredentialsException) throw new UserPasswordNotMatchException();
            else throw new ServiceException(e.getMessage());
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    @Override
    public void signup(LoginBody loginBody) {
        // 验证码校验
        validateCaptcha(loginBody.getCode(), loginBody.getUuid());
        // 登录前置校验
        signupCheck(loginBody);
        VrUser user = new VrUser();
        BeanUtils.copyProperties(loginBody, user);
        try {
            userService.insertVrUser(user);
        } catch (Exception e) {
            String str = "Duplicate column name '";
            String message = e.getMessage();
            if (message.contains(str)) {
                message = message.replace(str, "");
                String msg = message.substring(0, message.indexOf("'"));
                throw new ArgumentRepeatException(msg + "已存在！");
            }
            throw e;
        }
    }

    @Override
    public void register(VrUser user) {
        String username = user.getUsername(), password = user.getPassword();

        if (StringUtils.isEmpty(username))
        {
            throw new IllegalArgumentException("用户名不能为空");
        }
        else if (StringUtils.isEmpty(password))
        {
            throw new IllegalArgumentException("用户密码不能为空");
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new IllegalArgumentException("账户长度必须在2到20个字符之间");
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new IllegalArgumentException("密码长度必须在5到20个字符之间");
        }
        else if (!userService.checkUserNameUnique(user))
        {
            throw new IllegalArgumentException("保存用户'" + username + "'失败，注册账号已存在");
        }
        else
        {
            user.setNickname(username);
            user.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(user);
            if (!regFlag)
            {
                throw new IllegalArgumentException("注册失败,请联系系统管理人员");
            }
        }
    }

    private void signupCheck(LoginBody loginBody) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String email = loginBody.getEmail();
        String phoneNumber = loginBody.getPhoneNumber();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(email) || StringUtils.isEmpty(phoneNumber))
        {
            throw new ArgumentIllegalException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = cacheService.getCacheObject(verifyKey);
        cacheService.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new ArgumentIllegalException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
    }

    public void recordLoginInfo(Long userId)
    {
        VrUser sysUser = new VrUser();
        sysUser.setId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateVrUser(sysUser);
    }
}
